from caldavclientlibrary.protocol.webdav.report import Report
from caldavclientlibrary.protocol.http.data.string import RequestDataString
from StringIO import StringIO
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from caldavclientlibrary.protocol.caldav.definitions import caldavxml
from caldavclientlibrary.protocol.webdav.definitions import davxml
from caldavclientlibrary.protocol.utils.xmlhelpers import BetterElementTree

class ReportRange(Report):

	def __init__(self, session, url):
		super(ReportRange, self).__init__(session, url)

	def setRange(self, startdate, enddate):
		fields = ['SUMMARY','UID','DTSTART','DTEND','DURATION','RRULE','RDATE','EXRULE','EXDATE','RECURRENCE-ID']
		beginxml = Element(caldavxml.calendar_query)
		t1 = Element(davxml.prop)
		t2 = Element(caldavxml.calendar_data)
		t3 = Element(caldavxml.comp)
		t3.set("name","VCALENDAR")
		t4 = Element(caldavxml.comp)
		t4.set("name","VEVENT")
		props = []
		for field in fields:
			tag = Element(caldavxml.prop)
			tag.set("name", field)
			props.append(tag)
		for prop in props:
			t4.append(prop)
		t3.append(t4)
		t2.append(t3)
		t1.append(t2)
		beginxml.append(t1)
		reqfilter = Element(caldavxml.filter)
		f1 = Element(caldavxml.comp_filter)
		f1.set("name","VCALENDAR")
		f2 = Element(caldavxml.comp_filter)
		f2.set("name","VEVENT")
		f3 = Element(caldavxml.time_range)
		f3.set("start", startdate)
		f3.set("end", enddate)
		f2.append(f3)
		f1.append(f2)
		reqfilter.append(f1)
		beginxml.append(reqfilter)
		xmldoc = BetterElementTree(beginxml)
		os = StringIO()
		xmldoc.writeUTF8(os)
		self.request_data = RequestDataString(os.getvalue(), "text/xml charset=utf-8")
